package com.caipin.netty.decoder;


import com.caipin.domain.*;
import com.caipin.task.AsyncTask;
import com.caipin.utils.GsonHelper;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-03-17 15:18
 * @Description: TODO
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class DataMsgHandler extends SimpleChannelInboundHandler<String> {

    private static DataMsgHandler dataMsgHandler;


    @Autowired
    private AsyncTask asyncTask;

    @PostConstruct
    private void init() {
        dataMsgHandler = this;
    }

    private static Map<String, RegisterMessage> deviceInfoMap = new HashMap<>();
    private static Map<String, String> hostAndDeviceNumber = new HashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        // 注册
        Object devNumber = GsonHelper.getField(msg, "devNumber", GsonHelper.GSONTYPE.STRING);
        if (devNumber != null) {
            RegisterMessage registerMessage = GsonHelper.fromJson(msg, RegisterMessage.class);
            log.info(registerMessage.toString());
            long last_timestamp = System.currentTimeMillis() / 1000;
            RegisterMessageResult registerMessageResult = new RegisterMessageResult(0x0036, "Device registered successfully. ", 0x1020, last_timestamp);
            String result = GsonHelper.toJsonString(registerMessageResult);
            ctx.writeAndFlush(Unpooled.copiedBuffer(result.getBytes()));

            hostAndDeviceNumber.put(ctx.channel().remoteAddress().toString(), registerMessage.getDevNumber());

            // 记录设备信息
            deviceInfoMap.put(registerMessage.getDevNumber(), registerMessage);

            return;
        }


        // 心跳
        Object stats = GsonHelper.getField(msg, "stats", GsonHelper.GSONTYPE.INTEGER);
        if (stats != null) {
            long last_timestamp = System.currentTimeMillis() / 1000;
            Heartbeat hb = new Heartbeat(0x1020, last_timestamp);
            String result = GsonHelper.toJsonString(hb);
            ctx.writeAndFlush(Unpooled.copiedBuffer(result.getBytes()));

            return;
        }

        // 侦码数据
        List<DetectingCode> detectingCodeList = GsonHelper.parseNoHeaderArray(msg, DetectingCode.class);

        if (detectingCodeList != null && detectingCodeList.size() > 0) {
            for (DetectingCode detectingCode : detectingCodeList) {
                log.info(detectingCode.toString());
            }


            DetectingCodeResult detectingCodeResult = new DetectingCodeResult("", true, System.currentTimeMillis() / 1000, detectingCodeList.get(0).getUptime());
            String result = GsonHelper.toJsonString(detectingCodeResult);
            ctx.writeAndFlush(Unpooled.copiedBuffer(result.getBytes()));

            dataMsgHandler.asyncTask.postDetectionCodeDataToKafka(detectingCodeList,
                    deviceInfoMap.get(hostAndDeviceNumber.get(ctx.channel().remoteAddress().toString())));

        }
    }
}
